<template>
  <WrsDialog :visible="dialogVisible" :footer="false" width="1280px" title="修正档案" @cancel="dialogVisible = false">
    <template #dialog>
      <div ref="formRef1">
        <div class="title">修正方式</div>
        <a-radio-group name="radioGroup" v-model:value="formState.modifyType" @change="change">
          <a-radio :value="1">修正客户信息</a-radio>
          <a-radio :value="2">批量修正客户信息</a-radio>
          <a-radio :value="3">修正表卡信息</a-radio>
          <a-radio :value="4">批量修正表卡信息</a-radio>
        </a-radio-group>
        <div class="line"></div>
        <!--修正字段  -->
        <div class="title">修正字段</div>
        <!-- 单个修改 -->
        <template v-if="formState.modifyType == 1 || formState.modifyType == 3">
          <template v-for="(btn, index) in fields" :key="index">
            <a-button type="default" style="margin-right: 15px; width: 120px">
              {{ btn.fieldName }}
              <CloseCircleFilled @click="removeButton(index)" />
            </a-button>
          </template>
        </template>
        <!-- 批量修改 -->
        <template v-if="formState.modifyType == 2 || formState.modifyType == 4">
          <template v-for="(file, index) in fields" :key="index">
            <a-select v-if="file.fieldId == 'isSelfEmployed'" v-model:value="file.value" class="edittwo"
              placeholder="请选择个体工商户">
              <a-select-option :value="false">否</a-select-option>
              <a-select-option :value="true">是</a-select-option>
            </a-select>
            <a-cascader v-if="file.fieldId == 'regionId'" class="edittwo" show-search v-model:value="file.value"
              :options="companyAreaListTrue" placeholder="请选择所属行政区" />
            <a-input v-if="file.fieldId == 'remark'" v-model:value="file.value" class="edittwo"
              placeholder="请输入备注"></a-input>
            <a-cascader v-if="file.fieldId == 'professionId'" class="edittwo" show-search v-model:value="file.value"
              :options="professionVoList" @change="onChangePerfesionfile" placeholder="请选择行业分类" />
            <a-input v-if="file.fieldId == 'garbageNum'" v-model:value="file.value" class="edittwo"
              placeholder="请输入垃圾费户数"></a-input>

            <!-- 表卡 -->
            <a-select v-if="file.fieldId == 'isCharge'" v-model:value="file.value" class="edittwo"
              placeholder="请选择计费标志">
              <a-select-option :value="0">不计费</a-select-option>
              <a-select-option :value="1">计费</a-select-option>
            </a-select>
            <a-select v-if="file.fieldId == 'cardType'" v-model:value="file.value" class="edittwo" show-search
              placeholder="请选择表卡类型" :options="cardTypeOptions" :filter-option="filterOption"></a-select>
            <a-input v-if="file.fieldId == 'masterCardNo'" v-model:value="file.value" class="edittwo"
              placeholder="请输入总表编号"></a-input>
            <a-select v-if="file.fieldId == 'meterModelId'" v-model:value="file.value" class="edittwo" show-search
              placeholder="请输入水表型号" :options="meterModelVoList" :filter-option="filterOption"></a-select>
            <a-select v-if="file.fieldId == 'readCycleId'" v-model:value="file.value" class="edittwo" show-search
              placeholder="请选择抄表周期" :options="readCycleVoList" :filter-option="filterOption"></a-select>
            <a-select v-if="file.fieldId == 'pieceworkPriceId'" v-model:value="file.value" show-search
              placeholder="请输入抄表计件单价" :options="pieceworkPriceVoList" :filter-option="filterOption"></a-select>
            <CloseCircleFilled class="edittwo-closed" @click="removeButton(index)" />
          </template>
        </template>

        <a-dropdown :trigger="['click']">
          <a-button @click="handleVisibleChange">添加</a-button>
          <template #overlay>
            <a-menu :style="{ width: '200px' }">
              <a-input-search v-model:value="searchText" placeholder="请输入搜索内容" @change="handleSearch"
                style="margin-bottom: 8px" />
              <a-menu-item v-for="(item, index) in filteredItems" :key="index" @click="handleMenuItemClick(item)">
                {{ item.fieldName }}
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <!--修正明细  -->
        <div class="line"></div>
        <div class="title">修正明细</div>
        <a-button type="primary" v-if="formState.modifyType == 1 || formState.modifyType == 2"
          @click="addCustomer">添加客户</a-button>
        <a-button type="primary" v-if="formState.modifyType == 3 || formState.modifyType == 4"
          @click="clientModal">添加表卡</a-button>
        <a-form :model="table.dataSource" ref="tableFormRef">
          <WrsTable :scroll="{ x: 1200, y: 550 }" :dataSource="table.dataSource" :columns="table.columns"
            :showSelection="false" v-show="formState.modifyType == 1 || formState.modifyType == 2">
            <template #editSlot="{ text, record, index, column }">
              <template
                v-if="['customerName', 'customerAddress', 'garbageNum', 'installAddress', 'meterNo', 'prevReadDegree'].includes(column.dataIndex)">
                <span v-if="column.key">{{ text }}</span>
                <a-form-item v-else :name="[index, column.dataIndex]" :rules="{
                    message: `${column.title}不能为空!`,
                    required: true
                  }">
                  <a-input v-model:value="table.dataSource[index][column.dataIndex]"
                    :placeholder="`请输入${column.title}`"></a-input>
                </a-form-item>
              </template>
              <template v-if="column.dataIndex == 'isSelfEmployed'">
                <a-form-item :name="[index, 'isSelfEmployed']" :rules="{
                    message: '个体工商户不能为空!',
                    required: true
                  }">
                  <a-select v-model:value="table.dataSource[index].isSelfEmployed" style="width: 100%"
                    placeholder="请选择个体工商户">
                    <a-select-option :value="false">否</a-select-option>
                    <a-select-option :value="true">是</a-select-option>
                  </a-select>
                </a-form-item>
              </template>
              <template v-if="column.dataIndex == 'regionId'">
                <a-cascader v-model:value="table.dataSource[index].regionId" show-search :options="companyAreaListTrue"
                  placeholder="请选择所属行政区" />
              </template>
              <template v-if="column.dataIndex == 'remark'">
                <a-input v-model:value="table.dataSource[index].remark" placeholder="请输入备注"></a-input>
              </template>
              <template v-if="column.dataIndex == 'professionId'">
                <a-form-item :name="[index, 'professionId']" :rules="{
                    message: '行业分类不能为空!',
                    required: true
                  }">
                  <a-cascader show-search :options="professionVoList" @change="onChangePerfesion(index)"
                    placeholder="请选择行业分类" />
                </a-form-item>
              </template>
            </template>
          </WrsTable>
          <!-- 表卡 -->
          <WrsTable :scroll="{ x: 1200, y: 550 }" :dataSource="tableCard.dataSource" :columns="tableCard.columns"
            :showSelection="false" v-show="formState.modifyType == 3 || formState.modifyType == 4">
            <template #editSlot="{ text, record, index, column }">
              <template v-if="column.dataIndex == 'isCharge'">
                <a-form-item :name="[index, 'isCharge']" :rules="{
                    message: '计费标志不能为空!',
                    required: true
                  }">
                  <a-select v-model:value="table.dataSource[index].isCharge" style="width: 100%" placeholder="请选择计费标志">
                    <a-select-option :value="0">不计费</a-select-option>
                    <a-select-option :value="1">计费</a-select-option>
                  </a-select>
                </a-form-item>
              </template>
              <template v-if="column.dataIndex == 'cardType'">
                <a-form-item :name="[index, 'cardType']" :rules="{
                    message: '表卡类型不能为空!',
                    required: true
                  }">
                  <a-select v-model:value="table.dataSource[index].cardType" show-search placeholder="请选择表卡类型"
                    style="width: 100%" :options="cardTypeOptions" :filter-option="filterOption"></a-select>
                </a-form-item>
              </template>
              <template v-if="column.dataIndex == 'masterCardNo'">
                <a-input v-model:value="table.dataSource[index].masterCardNo" placeholder="请输入总表编号"></a-input>
              </template>
              <template v-if="column.dataIndex == 'meterModelId'">
                <a-form-item :name="[index, 'meterModelId']" :rules="{
                    message: '水表型号不能为空!',
                    required: true
                  }">
                  <a-select v-model:value="table.dataSource[index].readCycleId" show-search placeholder="请输入水表型号"
                    style="width: 200px" :options="meterModelVoList" :filter-option="filterOption"></a-select>
                </a-form-item>
              </template>
              <template v-if="column.dataIndex == 'meterDeviceCode'">
                <a-input v-model:value="table.dataSource[index].meterDeviceCode" placeholder="请输入IMEI"></a-input>
              </template>
              <template v-if="column.dataIndex == 'readCycleId'">
                <a-select v-model:value="table.dataSource[index].readCycleId" show-search placeholder="请选择抄表周期"
                  style="width: 200px" :options="readCycleVoList" :filter-option="filterOption"></a-select>
              </template>
              <template v-if="column.dataIndex == 'pieceworkPriceId'">
                <a-select v-model:value="table.dataSource[index].prevReadDegree" show-search placeholder="请输入抄表计件单价"
                  style="width: 200px" :options="pieceworkPriceVoList" :filter-option="filterOption"></a-select>
              </template>
            </template>
          </WrsTable>
        </a-form>

        <div class="line"></div>
        <!--修正原因  -->
        <div class="title">修正原因</div>
        <a-form layout="vertical" :model="formState" ref="formStateRef">
          <a-form-item label="修正原因" name="applyReason" :rules="[{ required: true, message: '修正原因不能为空!' }]">
            <a-input style="width: 20%; min-width: 300px" placeholder="请输入原因" v-model:value="formState.applyReason" />
          </a-form-item>
        </a-form>
      </div>
    </template>
    <template #foot1>
      <!-- <a-button @click="load">加载</a-button> -->
      <!-- <a-button @click="confirm('save')">暂存</a-button> -->
      <a-button @click="commitConfirm('commit')" type="primary">提交</a-button>
    </template>
  </WrsDialog>
</template>

<script setup>
import WrsTable from "@/components/WrsTable/index.vue";
import WrsDialog from "@/components/WrsDialog/index.vue";
import { reactive, h, ref, watch, defineExpose, computed } from "vue";
import { message, Modal } from "ant-design-vue";
import { CloseCircleFilled } from "@ant-design/icons-vue";
import Operations from "@/components/WrsTable/component/Operations.vue";

import { items1, items2, items3, items4, cardTypeOptions, getGroupChild } from "./index";
const props = defineProps({
  customerNo: {
    type: Number,
    default: 198055
  },
  companyId: {
    type: String,
    default: "1"
  }
});
const dialogVisible = ref(true);
const formState = ref({
  applyReason: null, //修正原因
  modifyType: 1
});
const defaultDataSource = ref([]); //初始化的数据
let defaultmodifyType = undefined; //初始化时默认选中的数据
const defaultCardDataSource = ref([]); //表卡选中的数据
const defaultCustomerDataSource = ref([]); //用户选中的数据
const companyAreaListTrue = ref(); //所属区域包含未禁用
const regionVoList = ref(); //所属行政区
const meterModelVoList = ref(); //水表型号
const pieceworkPriceVoList = ref(); //抄表计件类型
const readCycleVoList = ref(); //抄表周期
const professionVoList = ref(); //行业分类

const searchText = ref("");

//分组搜索
const fields = ref([]);

const items = ref(items1);
console.log('items', items.value)
const filteredItems = ref(items.value);
console.log(filteredItems.value)
// 监听单选
const change = (e) => {
  let val = e.target.value;
  switch (val) {
    case 1:
      items.value = items1;
      break;
    case 2:
      items.value = items2;
      break;
    case 3:
      items.value = items3;
      break;
    default:
      items.value = items4;
      break;
  }
  if (val === 1 || val === 2) {
    if (val === defaultmodifyType) {
      table.dataSource = [...defaultDataSource.value, ...defaultCustomerDataSource.value];
    } else {
      table.dataSource = defaultCustomerDataSource.value || [];
    }
    table.columns.splice(4, table.columns.length - 5);
  } else {
    if (val === defaultmodifyType) {
      tableCard.dataSource = [...defaultDataSource.value, ...defaultCardDataSource.value];
    } else {
      tableCard.dataSource = defaultCardDataSource.value || [];
    }

    tableCard.columns.splice(5, tableCard.columns.length - 6);
  }

  fields.value = [];
  filteredItems.value = items.value;
};
// 移除按钮的方法
const removeButton = (index) => {
  fields.value.splice(index, 1);
  if (formState.value.modifyType == 1) {
    table.columns.splice(index + 4, 1);
  } else if (formState.value.modifyType == 3) {
    tableCard.columns.splice(index + 5, 1);
  }
};

// 搜索处理函数
const handleSearch = (e) => {
  const val = e.target.value;
  if (val) {
    filteredItems.value = items.value.filter((item, index) => {
      return items.value[index].fieldName.toLowerCase().includes(val.toLowerCase());
    });
  } else {
    filteredItems.value = items.value;
  }
};
// 下拉菜单可见性变化时触发
const handleVisibleChange = () => {
  searchText.value = "";
  filteredItems.value = items.value;
};

// 菜单项点击事件
const handleMenuItemClick = (item) => {
  // 表格中修改
  let arr = fields.value.filter((obj) => {
    return obj.fieldName == item.fieldName;
  });
  if (arr.length) {
    return message.error(`${item.fieldName}已经添加，请勿重复添加`);
  } else {
    fields.value.push({
      fieldId: item.fieldId,
      fieldName: item.fieldName,
      value: undefined
    });
    if (formState.value.modifyType == 1) {
      table.columns.splice(length - 1, 0, {
        title: item.fieldName,
        dataIndex: item.fieldId,
        width: 220
      });
    } else if (formState.value.modifyType == 3) {
      console.log("1111", length - 1);
      tableCard.columns.splice(length - 1, 0, {
        title: item.fieldName,
        dataIndex: item.fieldId,
        width: 220
      });
    }
  }
};
/**
 * 表格
 * */
const table = reactive({
  dataSource: [],
  columns: [
    {
      title: "所属区域",
      dataIndex: "areaName",
      width: 120
    },
    {
      title: "客户编号",
      dataIndex: "customerNo",
      width: 120
    },
    {
      title: "客户名称",
      dataIndex: "customerName",
      width: 120,
      key: 1
    },
    {
      title: "客户地址",
      dataIndex: "customerAddress",
      width: 120,
      key: 1
    },
    {
      title: "操作",
      fixed: "right",
      width: 120,
      customRender({ text, record, index, column }) {
        return h(Operations, {
          btnList: [
            {
              btnName: "删除",
              click: () => {
                Modal.confirm({
                  title: "提示",
                  content: `确定删除该条信息?`,
                  icon() {
                    return h("i", {
                      class: "iconfont up-Attention"
                    });
                  },
                  onOk() {
                    table.dataSource.splice(index, 1);
                    message.success("删除成功");
                  }
                });
              }
            }
          ]
        });
      }
    }
  ]
});
const tableCard = reactive({
  dataSource: [],
  columns: [
    {
      title: "所属表册",
      dataIndex: "areaName",
      width: 120
    },
    {
      title: "表卡编号",
      dataIndex: "xxx",
      width: 120
    },
    {
      title: "客户编号",
      dataIndex: "customerNo",
      width: 120
    },
    {
      title: "客户名称",
      dataIndex: "customerName",
      width: 120,
    },
    {
      title: "客户地址",
      dataIndex: "customerAddress",
      width: 120,
    },
    {
      title: "客户地址1",
      dataIndex: "customerAddress1",
      width: 120,
    },
    {
      title: "操作",
      fixed: "right",
      width: 120,
      customRender({ text, record, index, column }) {
        return h(Operations, {
          btnList: [
            {
              btnName: "删除",
              click: () => {
                Modal.confirm({
                  title: "提示",
                  content: `确定删除该条信息?`,
                  icon() {
                    return h("i", {
                      class: "iconfont up-Attention"
                    });
                  },
                  onOk() {
                    tableCard.dataSource.splice(index, 1);
                    message.success("删除成功");
                  }
                });
              }
            }
          ]
        });
      }
    }
  ]
});
// 添加客户
const indexRef = ref();
const toPaymentNoRef = ref(); // 输入框
const selectFlag = ref("all"); //单single 全all
const addCustomer = () => {
  indexRef.value.modalInit(selectFlag.value);
};
const customerConfirm = (array) => {
  array = array.filter((itemA) => {
    const isExistInB = table.dataSource.find((itemB) => itemB.customerId === itemA.customerId);
    // 如果没有找到，则返回true以包含在结果数组中
    return !isExistInB;
  });
  if (formState.value.modifyType === defaultmodifyType) {
    table.dataSource = [...defaultDataSource.value, ...defaultCustomerDataSource.value, ...array];
  } else {
    table.dataSource = [...defaultCustomerDataSource.value, ...array];
  }
  defaultCustomerDataSource.value = JSON.parse(JSON.stringify(table.dataSource));
};
// 添加表卡
const clientModalRef = ref();
const clientModal = () => {
  clientModalRef.value.modalInit(selectFlag.value);
};
const cardModalConfirm = (array) => {
  array = array.filter((itemA) => {
    const isExistInB = tableCard.dataSource.find((itemB) => itemB.customerId === itemA.customerId);
    // 如果没有找到，则返回true以包含在结果数组中
    return !isExistInB;
  });
  if (formState.value.modifyType === defaultmodifyType) {
    tableCard.dataSource = [...defaultDataSource, ...defaultCardDataSource.value, ...array];
  } else {
    tableCard.dataSource = [...defaultCardDataSource.value, ...array];
  }
  defaultCardDataSource.value = JSON.parse(JSON.stringify(tableCard.dataSource));
};

const customerNo = ref(props.customerNo);
const companyId = ref(props.companyId);
const companyName = ref(undefined);
const result = ref({});
const config = ref({});
const busiType = 14; // * 14：档案修正
/**
 * 初始化加载
 * */
const busiId = ref(undefined);
const load = async () => {
  // console.log(busiId.value);
  // const res = await customerBusiQueryApi({ busiId: busiId.value });
};
const query = async () => {
  // const res = await customerBusiLoadApi({ busiType, customerNo: customerNo.value, companyId: companyId.value });
  // result.value = res.customerInfoBusi;
  // config.value = res.config
};
/**
 * 对下拉选择数据进行处理
 * */
const getAreaListTrue = async () => {
  // const res = await companyAreaQueryAreaApi({ companyId: companyId.value, disabled: true });
  // res.map((item) => {
  //   item.value = item.areaId;
  //   item.label = item.areaName;
  //   item.companyId = companyId.value;
  //   item.companyName = companyName.value;
  // });
  // companyAreaListTrue.value = res; //所属区域包含未禁用
};
const configLoad = async (config) => {
  // const res = await customerLoadApi({ companyId: companyId.value });
  regionVoList.value = [];
  config.meterModelVoList.map((item) => {
    //{型号编码}|{水表类型}|{水表口径}|{水表厂家}|{备注}
    item.value = item.meterModelId;
    item.label = item.meterModelCode + "|" + item.meterTypeName + "|" + item.meterCaliberName + "|" + item.meterFactoryName + (item.remark ? "|" + item.remark : "");
  });
  config.pieceworkPriceVoList.map((item) => {
    item.value = item.pieceworkPriceId;
    item.label = item.pieceworkPriceName + "|" + (item.price != null ? (item.price / 100).toFixed(2) : item.price);
  });
  config.readCycleVoList.map((item) => {
    item.value = item.readCycleId;
    item.label =
      item.remark +
      "|" +
      (item.months
        ? item.months
          .split(",")
          .sort((a, b) => {
            return a - b;
          })
          .join(",")
        : "");
  });
  readCycleVoList.value = config.readCycleVoList; //抄表周期
  meterModelVoList.value = config.meterModelVoList; //水表型号
  pieceworkPriceVoList.value = config.pieceworkPriceVoList; //抄表计件类型
  //行业分类
  console.log(config.professionVoList);
  let list = config.professionVoList;
  professionVoList.value = await getGroupChild(list);
  console.log(professionVoList.value);
};
const onChangePerfesion = (val, selectOption, index) => {
  formState.professionId = val[val.length - 1]
  formState.professionName = selectOption[val.length - 1].professionName
};
const onChangePerfesionfile = (val, selectOption) => {
  console.log(val, selectOption)
  // fields[index].value = val[val.length-1]
  // formState.professionName = selectOption[val.length-1].professionName
};
/**
 * 弹窗打开
 * */
const modalInit = async () => {
  // if (busiId.value) {
  //   await load();
  // } else {
  //   await query();
  // }
  // await configLoad(config.value.customerLoad);
  // await getAreaListTrue();
  // if (result.value.flowData) {
  //   console.log(111);
  //   formState.value.modifyType = result.value.flowData.modifyType;
  //   fields.value = result.value.flowData.fields;
  // if (result.value.flowData.modifyType == 1 || result.value.flowData.modifyType == 2) {
  //   table.dataSource = result.value.flowData.dataList;
  // } else {
  // tableCard.dataSource = result.value.flowData.dataList;
  // }
  //   defaultmodifyType = result.value.flowData.modifyType;
  //   defaultDataSource.value = JSON.parse(JSON.stringify(result.value.flowData.dataList));
  // }
  dialogVisible.value = true;
};
// 暂存提交
const commitConfirm = (type) => {
  Modal.confirm({
    title: "提示",
    content: `确定提交该节点？`,
    icon() {
      return h("i", {
        class: "iconfont up-Attention"
      });
    },
    onOk() {
      confirm(type);
    }
  });
};
const tableFormRef = ref({});
const formStateRef = ref({});
const confirm = async (type) => {
  await tableFormRef.value.validate();
  await formStateRef.value.validate();
  let arr = fields.value.filter((item) => item.fieldId === "masterCardNo");
  if (arr.length != 0) {
    if (formState.value.modifyType === 4 && arr[0].value === undefined) {
      return message.warning("总表编号不存在");
    } else if (formState.value.modifyType === 3) {
      table.dataSource.forEach((tr) => {
        if (!tr.masterCardNo) {
          return message.warning("总表编号不存在");
        }
      });
    }
  }
  let params = {
    busiType: 1,
    busiId: busiId.value,
    ...result.value,
    formData: {
      modifyType: formState.value.modifyType,
      applyReason: formState.value.applyReason,
      fields: fields.value,
      dataList: (formState.value.modifyType == 1 || formState.value.modifyType == 2) ? table.dataSource : tableCard.dataSource
    }
  };
  console.log("params", params);
  // if (type == "commit") {
  //   await customerBusiCommitApi(params);
  //   WrsMessageBox.success("提交成功");
  //   dialogVisible.value = false;
  // } else if (type == "save") {
  //   const res = await customerBusiSaveApi(params);
  //   busiId.value = res;
  // }
};
// 下拉、时间
const filterOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
defineExpose({
  modalInit
});
</script>

<style lang="less" scoped>
.ant-btn>.anticon+span,
.ant-btn>span+.anticon {
  margin-left: 8px;
  position: absolute;
  left: 105px;
  top: -7px;
  color: red;
}

.edittwo {
  width: 170px;
}

.edittwo-closed {
  position: relative;
  left: -7px;
  top: -15px;
  color: red;
}

.title {
  font-size: 15px;
  padding: 10px 0;
  font-weight: 600;
}

.line {
  border-bottom: 2px solid #f1f0f0;
  width: 100%;
  margin: 15px 0;
}

.search {
  .otherSearch {
    border-top: 1px solid transparent;
    margin-right: 10px;
    position: relative;

    .otherSearch-text {
      position: absolute;
      left: 16px;
      top: 5px;
      z-index: 1;
    }

    .ant-picker.ant-picker-range {
      padding-left: 90px;
    }

    :deep(.ant-picker-active-bar) {
      display: none;
    }
  }
}
</style>
